using System;
using UnityEngine;

namespace GameCore
{
    public class SimpleWorldItem : WorldItem
    {
        #region Display
        
        [Header("Display")]
        public SpriteRenderer backgroundSR;
        public SpriteRenderer itemSR;
        public Transform itemTransform;
        public Sprite sprite;
        
        public Vector2 targetWorldSize = new Vector2(1.5f, 1.5f);
        public Color colorNormal = new Color(0.9f, 0.9f, 0.9f);
        public Color colorSelected = new Color(0.5f, 0.5f, 0.5f);
        public Color colorHover = new Color(0.4f, 0.7f, 1f);
        public bool isSelected = false;

        private void ResizeItem()
        {
            var pixelSize = sprite.rect.size;
            var ppu = sprite.pixelsPerUnit;
            var units = pixelSize / ppu;
            var scale = targetWorldSize / units;
            var uniformScale = Mathf.Min(scale.x, scale.y);
            itemTransform.localScale = new Vector3(uniformScale, uniformScale, uniformScale);
            itemSR.sprite = sprite;
        }
        
        #endregion

        public void Start()
        {
            ResizeItem();
            if (itemData == null) ResetData();
        }

        private void OnValidate()
        {
            ResizeItem();
            gameObject.name = sprite.name;
            resourceID.id = sprite.name;
        }

        #region Mouse Interactions
        public void OnMouseEnter()
        {
            if (isSelected) return;
            backgroundSR.color = colorHover;
        }

        public void OnMouseExit()
        {
            if (isSelected) return;
            backgroundSR.color = colorNormal;
        }

        public override void OnClick()
        {
            PlayerInputHandler.BeginPlaceWorldItem(this);
        }
        
        #endregion

        public override void Select()
        {
            
            backgroundSR.color = colorSelected;
            isSelected = true;
        }

        public override void Deselect()
        {
            backgroundSR.color = colorNormal;
            isSelected = false;
        }
    }
}